layui.use(['form', 'table','xmSelect'], function () {
    var $ = layui.jquery,
        form = layui.form,
        table = layui.table;
    var xmSelect = layui.xmSelect;
    loadData(table);

    // 监听搜索操作
    form.on('submit(data-search-btn-user)', function (data) {
        //执行搜索重载
        table.reload('currentTableIdUserList', {
            page: {curr: 1},//重新从第 1 页开始
            where: data.field
        });

        return false;
    });

    /**
     * toolbar监听事件
     */
    table.on('toolbar(currentTableFilterUser)', function (obj) {
        if (obj.event === 'add') {  // 监听添加操作
            addUser(table);
        }

        if (obj.event === 'edit') {  // 监听添加操作
            init_update_user(table);
        }

        if (obj.event === 'delete') {  // 监听删除操作
            deleteUser(table);
        }

        if (obj.event === 'edit-user') {  // 编辑权限
            var selectdata = table.checkStatus('currentTableIdUserList').data;
            if(selectdata === null || selectdata.length === 0){
                lay_tishi("选择一条数据");
                return false;
            }
            openRoleList(selectdata, xmSelect, table);
        }
    });

    //监听表格复选框选择
    table.on('checkbox(currentTableFilterUser)', function (obj) {
        var cacheElement = table.cache['currentTableIdUserList'];
        tableCheckBoxOnly(obj, cacheElement);
    });

});


function deleteUser(table) {
    var selectdata = table.checkStatus('currentTableIdUserList').data;
    if (selectdata.length === 0) {
        lay_tishi("选择一条数据");
        return false;
    }
    if (selectdata.length > 1) {
        lay_tishi("有多条数据");
        return false;
    }
    layer.confirm('确认删除', function (index) {
        var param = "userId=" + selectdata[0].userId;
        var resultData = JSONAuthAjax(dl_coder_url.delete_user[0], dl_coder_url.delete_user[1], param);

        if (resultData.code === '200') {
            loadData(table);
            layer.close(index);
        }
    });
}

function init_update_user(table) {
    var selectdata = table.checkStatus('currentTableIdUserList').data;
    if (selectdata === null || selectdata.length === 0) {
        lay_tishi("选择一条数据");
        return false;
    }
    if (selectdata.length > 1) {
        lay_tishi("有多条数据");
        return false;
    }

    $("#userName").val(selectdata[0].userLoginName);
    $("#userId").val(selectdata[0].userId);
    $("#passWord").val(selectdata[0].userPassword);
    layer.open({
        type: 1,
        title: "修改用户",
        area: ['50%', '50%'],
        btn: ['确定', '取消'],
        content: $('#user-update-add-from'),
        yes: function (index, layero) {
            layui.use(['form'], function () {
                const form = layui.form;
                userFormValue(form, index, '2', table);
            });
        }
    });
}

function addUser(table) {
    $("#userId").val("");
    $("#userName").val("");
    $("#passWord").val("");
    layer.open({
        type: 1,
        title: "新增用户",
        area: ['50%', '50%'],
        btn: ['确定', '取消'],
        content: $('#user-update-add-from'),
        yes: function (index, layero) {
            layui.use(['form'], function () {
                const form = layui.form;
                userFormValue(form, index, '1', table);
            });
        }
    });
}


function userFormValue(form, index, type, table) {
    form.render();
    if (!form.validate('#user-update-add-from')) {
        return false;
    }
    const userId = $("#userId").val() == null ? null : parseInt($("#userId").val());
    const dataFormValue = {'userName': $('#userName').val(), 'userId':userId, 'passWord': $("#passWord").val()};
    var resultData;
    //新增
    if (type === "1") {
        resultData = JSONAuthAjax(dl_coder_url.add_user[0], dl_coder_url.add_user[1], dataFormValue);
    } else {
        //修改
        resultData = JSONAuthAjax(dl_coder_url.update_user[0], dl_coder_url.update_user[1], dataFormValue);
    }
    if (resultData.code === '200') {
        loadData(table);
        layer.close(index);
    }
}

function openRoleList(selectdata, xmSelect, table) {

    //获取所有角色
    var jsonAuthAjax = JSONAuthAjax(dl_coder_url.system_role_all[0], dl_coder_url.system_role_all[1], null);
    if(jsonAuthAjax.code !== '200'){
        return false;
    }

    //渲染多选
    var jsonAuthAjaxData = jsonAuthAjax.data;
    var selectDataList = [];
    for(var i = 0; i < jsonAuthAjaxData.length; i++){
        selectDataList.push({'name':jsonAuthAjaxData[i].roleName, 'value': jsonAuthAjaxData[i].id});
    }

    //设置多选框
    var splitInit;
    if(selectdata[0].roleIds){
        splitInit = selectdata[0].roleIds.split(",");
    }
    var arrSelect =selectDataList;
    xmSelect.render({
        el: '#user-select',
        toolbar: {show: true},
        tips: '选择权限',
        data: selectDataList,
        initValue: splitInit,
        on: function(data) {
            //arr:  当前多选已选中的数据
            arrSelect = data.arr;
        }
    });

    //打开弹出框
    layer.open({
        title: '添加权限用户',
        type: 1,
        area: ['30%', '50%'],
        btn: ['确定', '取消'],
        content: $('#user-select'),
        yes: function (index, layero) {
            if(arrSelect !=null || arrSelect.length !=0){
                var roleIds = [];
                for(var i=0;i<arrSelect.length; i++){
                    roleIds.push(arrSelect[i].value)
                }
                var paramData = {'userId':selectdata[0].userId, 'roleIds':roleIds};
                var updateResult = JSONAuthAjax(dl_coder_url.update_user_role[0], dl_coder_url.update_user_role[1],paramData);
                if(updateResult.code === '200'){
                    loadData(table);
                    layer.close(index);
                }
            }

        }
    });
}

function loadData(table, where) {
    table.render({
        elem: '#currentTableIdUserList',
        url: dl_coder_url.system_user[0],
        toolbar: '#toolbarDemoUser',
        method: dl_coder_url.system_user[1],
        where: where,
        contentType: 'application/json',
        dataType: 'json',
        request: {
            pageName: 'pageNo', //页码的参数名称，默认：page
            limitName: 'pageSize', //每页数据量的参数名，默认：limit
        },
        headers: headerMap,
        defaultToolbar: ['filter', 'exports', 'print', {
            title: '提示',
            layEvent: 'LAYTABLE_TIPS',
            icon: 'layui-icon-tips'
        }],
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "total": res.data.total, //解析数据长度
                "data": res.data.records, //解析数据列表
                "count": res.data.pages, //解析数据长度
            }
        },
        response: {
            statusName: 'code', //规定数据状态的字段名称，默认：code
            statusCode: 200,//规定成功的状态码，默认：0
            msgName: 'msg', //规定状态信息的字段名称，默认：msg
            countName: 'total', //规定数据总数的字段名称，默认：count
            dataName: 'data', //规定数据列表的字段名称，默认：data
        },
        cols: [[
            {type: "checkbox"},
            {field: 'userId', width: 80, title: 'ID', sort: true},
            {field: 'userLoginName', width: 200, title: '用户名'},
            {field: 'userPassword', width: 200, title: '用户密码'},
            {field: 'roleNames',  title: '用户权限'},
            {field: 'roleIds',  title: '用户权限Id', hide:true}
        ]],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 15,
        page: true,
        skin: 'line',
        even: true,
        size: 'sm',
        height: 'full-110' //高度最大化减去差值
    });
}